<template>
  <a-modal
    title='操作'
    style='top: 20px;'
    :width='1000'
    v-model='visible'
    :confirmLoading='confirmLoading'
    @ok='handleSubmit'
  >
    <a-form :form='form'>
      <a-form-item style='display:none'>
        <a-input v-decorator="['id']" />
      </a-form-item>
      <a-form-item style='display:none'>
        <a-input v-decorator="['version']" />
      </a-form-item>
      <div style='display: flex;margin-bottom: 20px'>
        <span style='width: 20px;display: block;font-size: 25px;color: #1890ff;font-weight: bold;'>|</span>
        <span style='display: block;margin-top: 11px;font-size: 15px'>设备管理</span>
      </div>
      <a-row>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属地区'>
            <a-select v-decorator="['tenantId', {rules: [{ required: true, message: '请选择所属地区' }]}]"
                      @change='selectTenant'
                      :disabled='tenantEnable'>
              <a-select-option v-for='item in tenantList' :key='item.id'>{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属园区'>
            <a-select v-decorator="['parkId', {rules: [{ required: true, message: '请选择所属园区' }]}]"
                      @change='selectPark'
                      :disabled='parkEnable'>
              <a-select-option v-for='item in parkList' :key='item.id'>{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属楼宇'>
            <a-select v-decorator="['buildingId', {rules: [{ required: true, message: '请选择所属楼宇' }]}]"
                      @change='selectBuilding'>
              <a-select-option v-for='item in buildingList' :key='item.id'>{{ item.buildingName }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属楼层'>
            <a-select v-decorator="['buildId',{rules: [{ required: true, message: '请选择所属楼层' }]}]"
                      placeholder='所属楼层'
                      @change='selectBuildingDetail'>
              <a-select-option v-for='item in buildingDetailList' :key='item.id' :value='item.id'>
                {{ item.floorName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属房间'>
            <a-select v-decorator="['roomId']"
                      placeholder='所属房间'
                      @change='selectRoom'>
              <a-select-option v-for='item in roomList' :key='item.id' :value='item.id'>
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='设备编号'>
            <a-input placeholder='设备编号'
                     v-decorator="['equipmentNum', {rules: [{required: true, message: '请输入设备编号'}]}]" />
          </a-form-item>
        </a-col>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='设备名称'>
            <a-input placeholder='设备名称'
                     v-decorator="['equipmentName',{rules: [{required: true, message: '请输入设备名称'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='设备类型'>
            <a-select v-decorator="['type',{rules: [{ required: true, message: '请选择设备类型'}]}]"
                      placeholder='请选择设备类型'>
              <a-select-option :value='0'>
                门禁
              </a-select-option>
              <a-select-option :value='1'>
                开门控制器
              </a-select-option>
              <a-select-option :value='2'>
                灯光
              </a-select-option>
              <a-select-option :value='3'>
                空调
              </a-select-option>
              <a-select-option :value='4'>
                窗帘控制器
              </a-select-option>
              <a-select-option :value='5'>
                电表
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='设备ip'>
            <a-input placeholder='设备ip' v-decorator="['ip',{rules: [{required: true, message: '请输入设备ip'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='设备状态'>
            <a-select v-decorator="['status',{rules: [{ required: true, message: '请选择设备状态'}]}]"
                      placeholder='请选择设备状态'>
              <a-select-option :value='0'>
                开启
              </a-select-option>
              <a-select-option :value='1'>
                损坏
              </a-select-option>
              <a-select-option :value='2'>
                离线
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='设备图片'>
            <!--        <a-input placeholder="设备图片" v-decorator="['pic',{rules: [{required: true, message: '请输入设备图片'}]}]"/>-->
            <a-upload
              v-decorator="['pic']"
              list-type='picture-card'
              class='avatar-uploader'
              :show-upload-list='false'
              :action='uploadUrl'
              :headers='headers'
              :before-upload='beforeUpload'
              @change='handleChange'
            >
              <img v-if='imageUrl' :src='imageUrl' style='width: 102px; height: 102px' />
              <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class='ant-upload-text'> 上传</div>
              </div>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <div style='display: flex;margin-bottom: 20px'>
      <span style='width: 20px;display: block;font-size: 25px;color: #1890ff;font-weight: bold;'>|</span>
      <span style='display: block;margin-top: 11px;font-size: 15px'>开门记录</span>
    </div>
    <a-table :columns='columns'
             size='default'
             ref='table'
             style='width: 800px;margin-left: 20px'
             :data-source='loadData'
    >
      <a slot='name' slot-scope='text'>{{ text }}</a>

    </a-table>

  </a-modal>
</template>
<script>
import { saveEquipment, get, recordByDeviceId, getRoomList } from '@/api/admin/meeting/equipment'
import pick from 'lodash.pick'
import { getFloorList, getRoomListByFloorId } from '@/api/admin/meeting/roomContent'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getInfo } from '@/api/login'
import { getTenantList } from '@/api/tenant'
import { getParkList } from '@/api/admin/park'
import { getBuildingList } from '@/api/admin/building'
import { getBuildingDetailList } from '@/api/admin/buildingDetail'

export default {
  name: 'EquipmentModal',
  props: {},
  components: {},
  data() {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      loadData: [],
      loading: false,
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      uploadUrl: process.env.VUE_APP_API_BASE_URL + '/api/dfs/upload',
      imageUrl: '',
      headers: {
        Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN)
      },
      confirmLoading: false,
      mdl: {},
      form: this.$form.createForm(this),
      columns: [
        {
          title: '开门时间',
          dataIndex: 'createTime'
        },
        {
          title: '开门方式',
          dataIndex: 'type',
          scopedSlots: {customRender:  'type'}

        },
        {
          title: '开门人',
          dataIndex: 'userName'
        }
      ],
      //
      userDetail: {},
      tenantList: [], // 地区
      parkList: [], // 园区
      buildingList: [], // 楼宇
      buildingDetailList: [], // 楼层
      roomList: [], // 房间
      tenantEnable: false,
      parkEnable: false
    }
  },
  beforeCreate() {
  },
  created() {

  },
  methods: {
    // 获取用户详细信息
    getUserDetail() {
      getInfo().then(res => {
        console.log('getUserDetail', res)
        this.userDetail = res
        // 园区：5
        if (this.userDetail.roleIds && this.userDetail.roleIds.length > 0 && this.userDetail.roleIds[0] == 5) {
          //
          // 判断：是新增就查询园区
          let { id } = this.mdl
          if (!id) {
            // 选择地区 -> 查询园区
            this.selectTenant(this.userDetail.tenantId)
            // 选择园区 -> 查询楼宇
            this.selectPark(this.userDetail.parkId)
          }
          //
          // 不可编辑
          this.tenantEnable = true
          this.parkEnable = true
          // 关联地区和园区
          this.mdl.parkId = this.userDetail.parkId
          this.mdl.tenantId = this.userDetail.tenantId
          this.form.setFieldsValue({
            parkId: this.mdl.parkId,
            tenantId: this.mdl.tenantId
          })
        }
      })
    },
    // 查询地区
    getTenantData() {
      getTenantList().then(res => {
        this.tenantList = res.rows
      })
    },
    // 选择地区 -> 查询园区
    selectTenant(id) {
      console.log('selectTenant', id)
      // 清空数据
      this.mdl.parkId = null // 园区
      this.mdl.buildingId = null // 楼宇
      this.mdl.buildId = null // 楼层
      this.mdl.roomId = null // 所属房间

      this.form.setFieldsValue({
        parkId: null, // 园区
        buildingId: null, // 楼宇
        buildId: null, // 楼层
        roomId: null // 所属房间
      })
      // 查询园区
      getParkList({
        tenantId: id
      }).then(res => {
        this.parkList = res.rows
      })
    },
    // 选择园区 -> 查询楼宇
    selectPark(id) {
      // 清空数据
      this.mdl.buildingId = null // 楼宇
      this.mdl.buildId = null // 楼层
      this.mdl.roomId = null // 所属房间

      this.form.setFieldsValue({
        buildingId: null, // 楼宇
        buildId: null, // 楼层
        roomId: null // 所属房间
      })
      // 查询楼宇
      getBuildingList({
        parkId: id
      }).then(res => {
        this.buildingList = res.rows
      })
    },
    // 选择楼宇 -> 查询楼层
    selectBuilding(id) {
      // 清空数据
      this.mdl.buildId = null // 楼层
      this.mdl.roomId = null // 所属房间

      this.form.setFieldsValue({
        buildId: null, // 楼层
        roomId: null // 所属房间
      })
      // 查询楼层
      getBuildingDetailList({
        buildingId: id
      }).then(res => {
        this.buildingDetailList = res.rows
      })
    },
    // 选择楼层 -> 查询房间
    selectBuildingDetail(buildingDetailId) {
      // 查询房间
      this.getRoomListByFloorIdMethod(buildingDetailId)
    },
    // 查询房间
    getRoomListByFloorIdMethod(buildingDetailId, id) {
      // 清空数据
      this.mdl.roomId = null // 所属房间

      this.form.setFieldsValue({
        roomId: null // 所属房间
      })
      // 查询房间
      getRoomListByFloorId({
        'id': id,
        'buildingDetailId': buildingDetailId
      }).then((res) => {
        this.roomList = res.data
      })
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 < 500
      if (!isLt2M) {
        this.$message.error('图片必须小于 500kb!')
      }
      return isJpgOrPng && isLt2M
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        const { form: { setFieldsValue } } = this
        const result = info.file.response
        // 设置值
        this.$nextTick(() => {
          setFieldsValue({
            // 设置相对路径
            pic: result.fileName
          })
        })
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl
          this.loading = false
        })
      }
    },
    add() {
      this.form.resetFields()
      this.mdl = {}
      this.edit({ id: 0 })
    },
    edit(record) {
      // 查询地区
      this.getTenantData()
      //
      this.mdl = Object.assign(this.mdl, record)
      let copyMdl = JSON.parse(JSON.stringify(this.mdl))
      // 查询用户信息
      this.getUserDetail()
      //
      if (record.id) {
        // 查询记录
        recordByDeviceId(record.id).then(res => {
          this.loadData = res.data
        })
        // 选择地区 -> 查询园区
        if (copyMdl.tenantId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.selectTenant(copyMdl.tenantId)
        }
        // 选择园区 -> 查询楼宇
        if (copyMdl.parkId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.selectPark(copyMdl.parkId)
        }
        // 选择楼宇 -> 查询楼层
        if (copyMdl.buildingId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.selectBuilding(copyMdl.buildingId)
        }
        // 选择楼层 -> 查询房间
        if (copyMdl.buildId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.getRoomListByFloorIdMethod(copyMdl.buildId, copyMdl.roomId)
        }
        // 防止替换
        this.mdl = JSON.parse(JSON.stringify(copyMdl))
      }
      if (this.mdl.pic) {
        this.imageUrl = process.env.VUE_APP_API_BASE_URL + this.mdl.pic
      } else {
        this.imageUrl = ''
      }
      //
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'id', 'type', 'equipmentName', 'status', 'createDate',
          'equipmentNum', 'ip', 'tenantId', 'parkId', 'buildingId', 'buildId', 'roomId', 'pic',
          'deleteFlag', 'createBy', 'createTime', 'updateBy', 'updateTime'))
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          this.confirmLoading = true
          saveEquipment(values).then(res => {
            if (res.code === 0) {
              this.$message.success('保存成功')
              this.$emit('ok')
              this.visible = false
            } else {
              this.$message.error(res.msg)
            }
          }).catch(() => {
            this.$message.error('系统错误，请稍后再试')
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}

function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
</script>
